import { action, observable } from 'mobx';
import { BaseViewModel, TextListener, speechApi, RobotApi, emojiPlayerModel } from 'orionos-eve-core';
import { ToastAndroid } from 'react-native'
import { demoModel } from './DemoModel';
import { addMoving, askQuestionV2, heartBeat, deviceRegister } from '../api/index.js'
import { ORGID } from '../utils/config'

const CryptoJS = require("crypto-js")

const DEVICE_SN = 'MC1BCN2K10025409M681'
/**
 * 业务逻辑
 */
export class DemoViewModel extends BaseViewModel {
    private heartBeatTimer: any
    private positionTimer: any
    private px: any
    private py: any
    private time: any
    private mTimer: any
    @observable private flag: boolean = false
    public ready: boolean = false
    @observable public playing: boolean = false
    @observable public voiceOn: boolean = true
    
    public constructor() {
        //super参数为ViewModel与Trigger相互通信的标识，必须保证与Trigger的一致
        super('demo');
    }

    public onStart() {
        this.heartBeatHandler()
        this.positionCatchHandler()
    }

    public onStop() {
        if(this.heartBeatTimer){
            clearInterval(this.heartBeatTimer)
        }
        if(this.positionTimer){
            clearInterval(this.positionTimer)
        }
        if(this.mTimer){
            clearTimeout(this.mTimer)
        }
    }
    public onHidden(): void{
        this.mTimer = setTimeout((): void=>{
            this.hideEmojiPlayer()
        }, 2000)
        this.setFlag(true)
    }
    public getFlag(): boolean {
        return this.flag
    }
    @action
    public setFlag(visibility: boolean): void{
        this.flag = visibility
    }
    public getVoiceOn(): boolean{
        return this.voiceOn
    }
    @action
    public setVoiceOn(voiceOn: boolean){
        this.voiceOn = voiceOn
    }
    //轨迹记录获取并上传
    private positionCatchHandler(){
        this.time = new Date()
        this.getCurPosition()
        this.positionTimer = setInterval((): void=>{
            this.getCurPosition()
        }, 5000)
    }
    private getCurPosition(){
        RobotApi.getPosition().then((result) => {
            try{
                let positionData = JSON.parse(result.message)
                let x = Number((positionData.px * 1).toFixed(3))
                let y = Number((positionData.py * 1).toFixed(3))
                if(x === this.px && y === this.py){
                    return
                }else{
                    this.px = x
                    this.py = y
                    let now = new Date()
                    let duration = (now.getTime() - this.time.getTime()) / 1000
                    this.time = now
                    this.uploadPosition(x, y, duration)
                }
            }catch(err){
                console.log('位置信息解析失败')
                console.log(err)
            }
        })
    }
    private uploadPosition(px: any, py: any, duration: any): void{
        let param = {
            movingtrail:{
                sn: DEVICE_SN,
                position: {
                    x: px,
                    y: py,
                    z: 0
                }
            },
            duration,
        }
        addMoving(param)
    }
    //设备注册并上传运行情况
    private heartBeatHandler(){
        let sn = DEVICE_SN
        let code =  Array.from({length: 9}, () => Math.floor(Math.random() * 36).toString(36)).join('')
        let check = CryptoJS.MD5(sn.slice(0, 3) + sn.slice(-3) + code).toString()
        deviceRegister({
            sn,
            // sn: SystemInfo.getDeviceSn(),
            name: '安徽省馆机器人',
            category: '移动盘点',
            appver: '0.0.2',
            model: 'ST-7000',
            organizationid: ORGID,
            code,
            check,
        }).then((res: any)=>{
            console.log(res)
            if(res.code === 0){
                demoModel.setToken(res.token)
                this.ready = true
                this.sendHeartBeat()
                this.heartBeatTimer = setInterval((): void=>{
                    this.sendHeartBeat()
                }, 60000)
            }else{
                ToastAndroid.showWithGravity('设备注册失败:' + res.msg, ToastAndroid.SHORT, ToastAndroid.CENTER)
                console.log(res.msg)
            }
        }).catch(err=>{
            console.log('获取token失败')
            console.log(err)
        })
        
        
    }
    private sendHeartBeat(){
        let param = {
            sn: DEVICE_SN,
            // sn: SystemInfo.getDeviceSn(),
        }
        heartBeat(param)
    }
    public towaitter(){
        this._apiTrigger(1003, '')
    }
    public totask(){
        this._apiTrigger(1007, '')
    }
    public exit() {
        //发送消息到Trigger中，eventId为消息id, data为携带的数据
        this._apiTrigger(1001, '');
    }
    
    public showSpeechText(text: string) {
        console.log('DemoVoice : set ' + text);
        demoModel.setInfoText(text);
    }
    public async chatHandler(text: string){
        if(!this.ready){
            return
        }
        // let param = {
        //     orgid: ORGID,
        //     bigmoderole: 'AILibrarian',
        //     question: text,
        //     isglobal: false,
        // }
        let param = {
            message: {
                content:{
                    type: 'text',
                    value: {
                        showText: text,
                    },
                }
            }
        }
        const res = await askQuestionV2(param)
        if(res.status === 0){
            if(res.data && res.data.content && res.data.content.length){
                let txtInfos = res.data.content.filter((el: any)=>el.dataType === 'txt')
                if(txtInfos.length){
                    let answer = txtInfos[0].data
                    this.answerQuestion(answer)
                }
            }
        }else{
            console.log('出错了')
            // console.log(res.message)
        }
        
    }
    public playTTS(){
        this.answerQuestion(demoModel.getAnswer())
    }
    public pauseTTS(){
        speechApi.stopTTS()
        this.setPlayState(false)
    }
    public getPlayState(){
        return this.playing
    }
    @action
    public setPlayState(playing: boolean){
        this.playing = playing
    }
    public answerQuestion(answer: any) {
        demoModel.setAnswer(answer)
        let listener = new TextListener()
        listener.setFinish(()=>{
            this.setPlayState(false)
            listener.removeListener()
        })
        this.playing = true
        speechApi.playText(listener.getId(), answer)
    }
    
}
